package brands

import (
	. "awesomeProject/goods-web/api"
	"awesomeProject/goods-web/forms"
	"awesomeProject/goods-web/global"
	"awesomeProject/goods-web/proto"
	"awesomeProject/user-web/api"
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func List(ctx *gin.Context) {

	pn := ctx.DefaultQuery("pn", "0")
	pnInt, _ := strconv.Atoi(pn)
	pSize := ctx.DefaultQuery("psize", "10")
	pSizeInt, _ := strconv.Atoi(pSize)

	rsp, err := global.GoodsSrvClient.BrandList(context.Background(), &proto.BrandFilterRequest{
		Pages:       int32(pnInt),
		PagePerNums: int32(pSizeInt),
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	rspMap := make(map[string]interface{})
	rspMap["total"] = rsp.Total

	brandInfos := make([]interface{}, 0)
	for _, data := range rsp.Data[pnInt : pnInt*pSizeInt+pSizeInt] {
		//for _, data := range rsp.Data {

		brandInfo := make(map[string]interface{})
		brandInfo["name"] = data.Name
		brandInfo["id"] = data.Id
		brandInfo["logo"] = data.Logo

		brandInfos = append(brandInfos, brandInfo)
	}
	rspMap["data"] = brandInfos
	ctx.JSON(http.StatusOK, brandInfos)
}

func New(ctx *gin.Context) {

	brandForm := forms.BrandForm{}
	if err := ctx.ShouldBind(&brandForm); err != nil {
		HandleValidateError(err, ctx)
		return
	}

	rsp, err := global.GoodsSrvClient.CreateBrand(context.Background(), &proto.BrandRequest{
		Name: brandForm.Name,
		Logo: brandForm.Logo,
	})
	if err != nil {
		HandleGrpcErrorToHttp(err, ctx)
	}

	rspMap := make(map[string]interface{})

	rspMap["id"] = rsp.Id
	rspMap["name"] = rsp.Name
	rspMap["logo"] = rsp.Logo

	ctx.JSON(http.StatusOK, rspMap)
}

func Delete(ctx *gin.Context) {

	idStr := ctx.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		HandleGrpcErrorToHttp(err, ctx)
		return
	}

	_, err = global.GoodsSrvClient.DeleteBrand(context.Background(), &proto.BrandRequest{
		Id: int32(id),
	})
	if err != nil {
		HandleGrpcErrorToHttp(err, ctx)
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "删除成功",
	})
}

func Update(ctx *gin.Context) {

	brandForm := forms.BrandForm{}
	if err := ctx.ShouldBind(&brandForm); err != nil {
		HandleValidateError(err, ctx)
		return
	}

	idStr := ctx.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		HandleGrpcErrorToHttp(err, ctx)
		return
	}

	_, err = global.GoodsSrvClient.UpdateBrand(context.Background(), &proto.BrandRequest{
		Id:   int32(id),
		Name: brandForm.Name,
		Logo: brandForm.Logo,
	})
	if err != nil {
		HandleGrpcErrorToHttp(err, ctx)
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "更新成功",
	})

}
